/*
 * @Author: bamboo
 * @Date: 2023-02-18 09:05:19
 * @LastEditors: bamboo 815070110@qq.com
 * @LastEditTime: 2023-02-18 10:00:45
 * @FilePath: \vue3-cart\src\store\cart.ts
 * @Description: 
 */

import { defineStore } from "pinia"

export const useCart = defineStore('cart', {
  state: () => ({
    isEdit: false,
    list: [
      {
        id: 1,
        checked: false,
        price: 180,
        title: '华为智慧屏',
        desc: '这是一个电视',
        cover: '../../static/ceui.png',
        num: 1,
        minNum: 1,
        maxNum: 999,
      },
      {
        id: 19,
        checked: false,
        price: 100,
        title: 'ikbc键盘',
        desc: '这是一个键盘',
        cover: '../../static/ceui.png',
        num: 1,
        minNum: 1,
        maxNum: 999,
      },
      {
        id: 29,
        checked: false,
        price: 280,
        title: '西铁城手表',
        desc: '这是一个光动能手表',
        cover: '../../static/ceui.png',
        num: 4,
        minNum: 1,
        maxNum: 999,
      },
    ],
    selectedAll: [] as number[] //放获取的id值
  }),
  actions: {
    //执行全选或全不选
		doSelectAll() {
			this.checkedAll ? this.unSelectAll() : this.selectAll()
		},
		//全选商品的方法
		selectAll() {
			this.selectedAll = this.list.map(curr => {
				curr.checked = true
				return curr.id
			})
		},
    //商品全不选的方法
		unSelectAll() {
			this.selectedAll = []
			this.list.map(curr => curr.checked = false)
		},
    //单选商品
		selectItem(index:number) {
			let id = this.list[index].id
			let i = this.selectedAll.indexOf(id)
			if (i > -1) {
				this.list[index].checked = false
				this.selectedAll.splice(i, 1)
			} else {
				this.list[index].checked = true
				this.selectedAll.push(id)
			}
		},
    //删除商品
		delGoods() {
			this.list = this.list.filter(v => {
				return this.selectedAll.indexOf(v.id) === -1 //返回 过滤后 不相等的
			})
			// console.log(a);
			//删掉已经选中的数组
			this.selectedAll = []
		},
  },
  getters:{
    disSelect(state){
     return state.list.length === 0 ? true : false
    },
    		//计算总价
		totalPrice(state) {

			//reduce
			if (state) {
				return state.list.reduce((acc, curr) => {
					if (curr.checked) {
						return acc + curr.price * curr.num
					} else {
						return acc
					}
				}, 0)
			}
		},
    //全选
		checkedAll(state) {
			return state.selectedAll.length === state.list.length
		},
  }
})